/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.kaijie.admin.modules.oss.controller;

import com.kaijie.admin.common.utils.MD5Util;
import com.kaijie.admin.common.utils.R;
import com.kaijie.admin.modules.oss.cloud.AliyunCloudStorageService;
import com.kaijie.admin.modules.oss.cloud.CloudStorageConfig;
import com.kaijie.admin.modules.oss.cloud.OSSFactory;
import com.kaijie.admin.modules.oss.entity.SysOssEntity;
import com.kaijie.admin.modules.oss.service.SysOssService;
import com.kaijie.exception.RRException;
import com.kaijie.utils.DateUtils;
import com.kaijie.utils.PageUtils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * 文件上传
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/oss/file")
public class OssFileController {
    @Autowired
    private SysOssService sysOssService;
    //文件上传
    @Autowired
    private CloudStorageConfig cloudStorageConfig;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("oss:file:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = sysOssService.queryPage(params);

        return R.page(page);
    }


    /**
     * 上传文件
     */
    @RequestMapping("/upload")
    //@RequiresPermissions("oss:file:upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
		// 获取原始名字
		String fileName = file.getOriginalFilename();
		// 获取后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		// 文件保存路径
		String filePath = "c:/springboot_installl/img/";
//D:\wechat-betababy-master\miniprogram\pages\images
		// 文件重命名，防止重复
		//String uuid=""+UUID.randomUUID();uuid=uuid.substring(2, 6);
		String uuid="";
		String img=fileName;//uuid+"@"+fileName;
		fileName = filePath+img;
		File dest = new File(fileName);
		// 判断路径是否存在，如果不存在则创建
		if(!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			// 保存到服务器中
			file.transferTo(dest);
		}catch (Exception e) {
			e.printStackTrace();
		}
        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl("http://localhost:8089/admin/comment/gettu?name="+file.getOriginalFilename());
        ossEntity.setCreateDate(new Date());
        sysOssService.save(ossEntity);

        return R.ok().put("url", "http://localhost:8089/admin/comment/gettu?name="+file.getOriginalFilename());
    }
    /**
     * 职校上传文件
     */
    @RequestMapping("/uploadz")
    //@RequiresPermissions("oss:file:upload")
    public R uploadz(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
		String fileName = file.getOriginalFilename();// 获取原始名字
		String suffixName = fileName.substring(fileName.lastIndexOf(".")+1);// 获取后缀名
		String timeyyr="";
		Calendar now = Calendar.getInstance();
		SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMdd");
		timeyyr=sdFormatter.format(Calendar.getInstance().getTime()); 
		
		
		// 文件保存路径
		String filePath = "D:/hcportal/public/upload/default/"+timeyyr+"/";
		// 文件重命名，防止重复
		String uuid=UUID.randomUUID().toString();
		
		String img=fileName;//uuid+"@"+fileName;
		fileName = filePath+uuid+"."+suffixName;
		File dest = new File(fileName);
		// 判断路径是否存在，如果不存在则创建
		if(!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			// 保存到服务器中
			file.transferTo(dest);
		}catch (Exception e) {
			e.printStackTrace();
		}
			

        return R.ok().put("url", "default/"+timeyyr+"/"+uuid+"."+suffixName);
    }
    /**
     * 微信上传图片
     */
    @RequestMapping("/uploadimg")
    //@RequiresPermissions("oss:file:upload")
    public String uploadimg(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
		// 获取原始名字
		String fileName = file.getOriginalFilename();
		// 获取后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		// 文件保存路径
		String filePath = "c:/springboot_installl/img/";
		//D:\wechat-betababy-master\miniprogram\pages\images
		String uuid="";
		String img=fileName;//uuid+"@"+fileName;
		fileName = filePath+img;
		File dest = new File(fileName);
		// 判断路径是否存在，如果不存在则创建
		if(!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			// 保存到服务器中
			file.transferTo(dest);
		}catch (Exception e) {
			e.printStackTrace();
		}
        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl("http://localhost:8089/admin/comment/gettu?name="+file.getOriginalFilename());
        ossEntity.setCreateDate(new Date());
        sysOssService.save(ossEntity);

        return "http://localhost:8089/admin/comment/gettu?name="+file.getOriginalFilename();
    }
    @RequestMapping("/upload2")
    @RequiresPermissions("oss:file:upload")
    public R imgUpload(@RequestParam("file") MultipartFile file) {
        String filePath ="" ;
        String fileName = "";
        String serverName = "";
        String suffix = "";
        String cloudPath = "";
        try{
            if(file != null && file.getSize()<= (20*1024*1024)){
                //取得当前上传文件的文件名称
                fileName = file.getOriginalFilename();
                if(!"".equals(fileName.trim())){
                    // 文件保存路径
                    Random rand = new Random();
                    String ranName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"_"+rand.nextInt(1000);
                    serverName = ranName + fileName.substring(fileName.lastIndexOf("."));
                    suffix = fileName.substring(fileName.lastIndexOf("."));

                    //上传阿里云OSS
                    //cloudPath = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);
                    cloudPath = new AliyunCloudStorageService(cloudStorageConfig).uploadSuffix(file.getBytes(), suffix);

                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("云"+cloudPath);
        
      //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(cloudPath);
        ossEntity.setCreateDate(new Date());
        sysOssService.save(ossEntity);

        return R.ok().put("url", cloudPath);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("oss:file:delete")
    public R delete(@RequestBody Long[] ids) {
        sysOssService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
